import { Map, View, Feature } from 'ol'
// import { Tile as TileLayer } from 'ol/layer'
// import { XYZ, TileArcGISRest } from 'ol/source'
import Link from 'ol/interaction/Link.js'
import { XYZ } from 'ol/source'
import { Style, Icon, Stroke, Fill, Text } from 'ol/style'
import { fromLonLat, toLonLat, transform } from 'ol/proj'
import { Point, LineString } from 'ol/geom'
import VectorSource from 'ol/source/Vector'
// import VectorLayer from 'ol/layer/Vector'
// import WebGLPointsLayer from 'ol/layer/WebGLPoints'
import {
  Heatmap as HeatmapLayer,
  Tile as TileLayer,
  Vector as VectorLayer,
  WebGLPoints as WebGLPointsLayer
} from 'ol/layer'
import { Modify, Draw } from 'ol/interaction'
import Overlay from 'ol/Overlay'
import Collection from 'ol/Collection'
import GeoJSON from 'ol/format/GeoJSON.js'
import TopoJSON from 'ol/format/TopoJSON.js'
import { boundingExtent } from 'ol/extent'
import { fromExtent } from 'ol/geom/Polygon'
import LinearRing from 'ol/geom/LinearRing.js'
import { FullScreen, defaults as defaultControls } from 'ol/control.js'

import $tool from '@/utils/tool'

import _ from 'lodash'

export default {
  // 设置图层样式
  getLayer() {
    const layer = [
      new TileLayer({
        preload: Infinity,
        source: new XYZ({
          url: import.meta.env.VITE_DARK_MAP_URL
        })
      }),
      new TileLayer({
        preload: Infinity,
        source: new XYZ({
          url: import.meta.env.VITE_LIGHT_MAP_URL
        })
      })
    ]
    return layer
  },

  // 创建地图
  createMap(container: string, config: object) {
    return new Map({
      layers: this.getLayer(),
      target: container,
      view: new View(config),
      // interactions: createSelector(), // 创建选择和拖拽组件
      controls: defaultControls({ zoom: false, rotate: false, attribution: false }).extend([
        new FullScreen({
          source: 'fullscreen'
        })
      ])
    })
  },

  //
  createLink() {
    return new Link()
  },

  // 创建矢量图层
  createVectorLayer(config: object) {
    return new VectorLayer(config)
  },

  // 创建海量点图层
  createWebGLPointsLayer(config: any) {
    return new WebGLPointsLayer(config)
  },

  // 创建热力图图层
  createHeatmapLayer(config: object) {
    return new HeatmapLayer(config)
  },

  // 创建矢量源
  createVectorSource(type: string) {
    if (type === 'line') {
      return new VectorSource({
        wrapX: false
      })
    } else if (type === 'polygon') {
      return new VectorSource({
        format: new GeoJSON()
      })
    } else if (type === 'area') {
      return new VectorSource({
        format: new GeoJSON()
      })
    } else {
      return new VectorSource({})
    }
  },

  // 创建Modify
  createModify(feature: any) {
    return new Modify({
      features: new Collection([feature])
    })
  },

  // 创建Draw
  createDraw(type: any) {
    return new Draw({
      source: new VectorSource(),
      type: type
      // freehand: true
    })
  },

  // 创建Point
  createPoint(point: any, value: any = null) {
    const uuid = $tool.createUUID()

    const feature = new Feature({
      type: 'point',
      geometry: new Point(this.fromLonLat(point)),
      id: uuid,
      value: value
    })

    feature.setId(uuid)

    return feature
  },

  // 创建Line
  createLine(line: any, value: any = null) {
    const uuid = $tool.createUUID()
    const arr = [] as any

    _(line).forEach((i: any) => {
      arr.push(this.fromLonLat(i))
    })

    const feature = new Feature({
      type: 'line',
      geometry: new LineString(arr, 'XY'),
      id: uuid,
      value: value
    })

    feature.setId(uuid)

    return feature
  },

  // 创建Polygon
  createPolygon(polygon: any, value: any = null) {
    const json = this.setGeoJson(polygon[0], value)

    return new GeoJSON().readFeatures(json)
  },

  // 创建Mask
  createMask() {
    return new VectorLayer({
      zIndex: 3,
      source: new VectorSource(),
      style: new Style({
        fill: new Fill({
          color: 'rgba( 0, 0, 0, 0.7)'
        }),
        stroke: new Stroke({
          color: '#f4b49f',
          width: 3
        })
      })
    })
  },

  // 创建Track
  createTrack(track: any) {
    const uuid = $tool.createUUID()

    const feature = new Feature({
      type: 'route',
      geometry: track,
      id: uuid
    })

    feature.setId(uuid)

    return feature
  },

  // 创建Area
  createArea(url: string) {
    const aa = new URL(url, import.meta.url).href

    console.log(new URL(url, import.meta.url))

    //  return new GeoJSON().readFeatures(aa)

    const source = new VectorSource({
      url: aa,
      format: new GeoJSON()
    })

    return source
  },

  createGeometry(geometry: any) {
    return new Feature({
      geometry: geometry
    })
  },

  // 创建Overlay
  createOverlay(container: any, offset: any) {
    return new Overlay({
      element: container,
      autoPan: true,
      positioning: 'center-center',
      offset: offset
    })
  },

  // 创建GeoJSON
  createGeoJSON(json: any) {
    return new GeoJSON().readFeatures(json)
  },

  erase(geom: any) {
    const extent = [-180, -90, 180, 90]
    const polygonRing = fromExtent(extent)
    const coords = geom.getCoordinates()
    coords.forEach((coord: any) => {
      const linearRing = new LinearRing(coord[0])
      polygonRing.appendLinearRing(linearRing)
    })
    return polygonRing
  },

  setMultiPolygon(data: any) {
    const uuid = $tool.createUUID()

    const json = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'MultiPolygon',
            coordinates: [data]
          },
          id: uuid
        }
      ]
    }

    return json
  },

  // 设置GeoJson格式
  setGeoJson(data: any, value: any = null) {
    const uuid = $tool.createUUID()
    const arr = [] as any

    _(data).forEach((item: any) => {
      arr.push(this.fromLonLat(item))
    })

    const json = {
      type: 'FeatureCollection',
      crs: {
        type: 'name',
        properties: {
          name: 'EPSG:3857'
        }
      },
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'Polygon',
            coordinates: [arr]
          },
          properties: {
            type: 'polygon',
            id: uuid,
            value: value
          },
          id: uuid
        }
      ]
    }

    return json
  },

  // 获取缩放级别
  getZoom(map: any) {
    return map.getView().getZoom()
  },

  // 设置缩放级别
  setZoom(map: any, num: number) {
    map.getView().setZoom(num)
  },

  // 将坐标从经度/纬度转换为不同的投影
  fromLonLat(point: any) {
    return fromLonLat(this.transform4326(point))
  },

  // 将坐标转换为经度/纬度
  toLonLat(point: any) {
    return toLonLat(point)
  },

  // 设置图层样式
  setStyle(event: object) {
    return new Style(event)
  },

  // 设置直线样式
  setStroke(color: string, width: number) {
    return new Stroke({
      color: color,
      width: width
    })
  },

  setFill(color: string) {
    return new Fill({
      color: color
    })
  },

  // 设置图标样式
  setIcon(event: object) {
    return new Icon(event)
  },

  //
  setPoint(point: any) {
    return new Point(point)
  },

  // 设置文本样式
  setText(text: string, color: string, offsetX: number = 0, offsetY: number = 0) {
    return new Text({
      font: '14px sans-serif',
      textAlign: 'center',
      justify: 'center',
      text: text,
      offsetX: offsetX,
      offsetY: offsetY,
      fill: new Fill({
        color: color
      })
    })
  },

  // 获取经纬度数组中的最大经纬度和最小经纬度
  getAreaLonLat(areaPoints: any) {
    return boundingExtent(areaPoints)
  },

  transform3857(point: any) {
    return transform(point, 'EPSG:4326', 'EPSG:3857')
  },

  transform4326(point: any) {
    return transform(point, 'EPSG:3857', 'EPSG:4326')
  },

  getLonLat(coordinates: any) {
    const arr = [] as any

    _(coordinates).forEach((item: any) => {
      arr.push(this.toLonLat(item))
    })

    return arr
  },

  a(json: any) {
    // console.log('111111111')
    // const json = require('../json/410100_full.json')
    // const features = (new GeoJSON({ featureProjection: 'EPSG:3857' })).readFeatures(json)
    // var vectorSource = new VectorSource({ features: features })
    // const lineLayer = new VectorLayer({ zIndex: 99, source: vectorSource })

    console.log(json)

    const vectorSource = new VectorSource({
      features: new GeoJSON({ featureProjection: 'EPSG:3857' }).readFeatures(json)
    })

    return vectorSource
  },

  aa(url: string) {
    const source = new VectorSource({
      url: url,
      format: new GeoJSON()
    })

    return source
  },

  aaaa() {
    const style = new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.6)'
      }),
      stroke: new Stroke({
        color: '#319FD3',
        width: 1
      })
    })

    const vector = new VectorLayer({
      source: new VectorSource({
        url: 'https://gw.alipayobjects.com/os/alisis/geo-data-v0.1.2/choropleth-data/country/100000_country_province.topo.json',
        format: new TopoJSON({}),
        overlaps: false
      }),
      style: style
    })

    console.log(vector)

    return vector
  }
}
